package com.pijunn.label

import grails.validation.Validateable;

import com.pijunn.users.AppUser;

@Validateable
class AssignLabelsCommand {
	Long startSerialNumber
	Long endSerialNumber
	AppUser user
	
	static constraints = {
		startSerialNumber (blank: false)
		endSerialNumber (blank:false, validator:{val, obj ->
			if (val < obj.startSerialNumber)
				   return "label.endValue.before.startValue"
				   
			// Duplicate check
			def res = Label.findAllBySerialNumberBetween(obj.startSerialNumber, val)
			def quantity = obj.endSerialNumber - obj.startSerialNumber + 1
			if (res?.size() != quantity)
				return "assign.missing.range"
				
			// Available check
			res = Label.findAllBySerialNumberBetweenAndRegisteredToIsNotNull(obj.startSerialNumber, val)
			if (res)
				return ["assign.duplicate.assignment", res.collect { it.serialNumber }?.join(',')]
		})
		user (blank: false, validator:{val, obj -> 
			if (!val.id)
				return 'assign.missing.user'
		})
	}
}
